package cn.ruc.dbiir.neo4j;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;


public class Neo4jDB {

	public static void main(String[] args) {
				try {
					getNeo4jConnection();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		
//		getConnection();
	}

	public static Connection getNeo4jConnection() throws SQLException {
//		Connection conn = DriverManager.getConnection("jdbc:neo4j:bolt://10.77.50.193:5002/","neo4j","xiaojian");
		Connection conn = DriverManager.getConnection("jdbc:neo4j:bolt://127.0.0.1:7687/","neo4j","xiaojian");
//		System.out.println(conn);
		try{
			Statement statement = conn.createStatement();
			ResultSet resultSet = statement.executeQuery("MATCH (n:item{plm_m_oid:'796'})-[rel*]-(m) RETURN n.plm_m_oid,rel,m limit 20");
			while (resultSet.next()){
				System.out.println(resultSet.getString(1));
			}
		}catch (Exception e){
			e.printStackTrace();
		}

		return conn;
	}

	public static void getConnection() {
		
		GraphDatabaseService graphDb = new GraphDatabaseFactory().
				newEmbeddedDatabase(new File("/Users/mark/Documents/MasterLife/GraphDB/neo4j-community-3.4.6/data/databases/test2.db"));
//				newEmbeddedDatabaseBuilder(new File("/Users/mark/Documents/MasterLife/GraphDB/neo4j-community-3.4.6/data/databases/test2.db"))
//				.setConfig(GraphDatabaseSettings.allow_store_upgrade, "true").newGraphDatabase();
		registerShutdownHook( graphDb );
		
		Transaction tx = graphDb.beginTx();
		Node firstNode = graphDb.createNode();
		firstNode.setProperty( "message", "Hello, " );
		Node secondNode = graphDb.createNode();
		secondNode.setProperty( "message", "World!" );

		Relationship relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
		relationship.setProperty( "message", "brave Neo4j " );

		System.out.print( firstNode.getProperty( "message" ) );
		System.out.print( relationship.getProperty( "message" ) );
		System.out.print( secondNode.getProperty( "message" ) );
		tx.success();
	}

	private static void registerShutdownHook( final GraphDatabaseService graphDb ) {
		// Registers a shutdown hook for the Neo4j instance so that it
		// shuts down nicely when the VM exits (even if you "Ctrl-C" the
		// running example before it's completed)
		Runtime.getRuntime().addShutdownHook( new Thread()
		{
			@Override
			public void run()
			{
				graphDb.shutdown();
			}
		} );
	}

}

enum RelTypes implements RelationshipType {
	KNOWS
}
